package cn.ivicar.oss.controller;

import cn.com.carsmart.exception.CarsmartException;
import cn.com.carsmart.ws.ibatis.model.BaseExample;
import cn.com.carsmart.ws.model.DeviceSetting;
import cn.com.carsmart.ws.model.ParamDefinition;
import cn.com.carsmart.ws.service.DeviceSettingManager;
import cn.com.carsmart.ws.service.ParamDefinitionManager;
import cn.ivicar.oss.entity.ResponseEntity;
import com.google.inject.Inject;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author: Administrator
 * @Description:参数信息控制层
 * @Date: Created in 2017/5/16
 */
public class ParamController {

    @Inject
    private ParamDefinitionManager paramDefinitionManager;

    @Inject
    private DeviceSettingManager deviceSettingManager;

    /*
    paramDefinition中添加数据
     */
    public ResponseEntity addParamDefinition(JSONObject jsonObject) throws CarsmartException {

        ResponseEntity responseEntity = new ResponseEntity();
        if (jsonObject != null && jsonObject.keySet().size() > 0) {

            String paramType = jsonObject.optString("parmType", null);

            //添加成功
            if (StringUtils.isNotBlank(paramType)) {
                String name = jsonObject.optString("name", null);
                int value = jsonObject.optInt("value", 0);
                if (StringUtils.isNotBlank(name)) {
                    ParamDefinition paramDefinition = new ParamDefinition();
                    paramDefinition.setName(name);
                    paramDefinition.setValue(value);
                    paramDefinition.setDeviceParamId(Integer.parseInt(paramType));
                    paramDefinition.setCreated(new Date());
                    paramDefinition.setUpdated(new Date());

                    this.paramDefinitionManager.insert(paramDefinition);
                    return responseEntity;
                }
            }
        }
        responseEntity.setCode(400);
        responseEntity.setMessage("新增失败！参数不正确！");//添加失败
        return responseEntity;

    }

    /*
    更新paramDefinition表
     */
    public ResponseEntity updateParamDefinition(JSONObject jsonObject) throws CarsmartException {

        ResponseEntity responseEntity = new ResponseEntity();
        if (jsonObject != null && jsonObject.keySet().size() > 0) {

            String id = jsonObject.optString("id", null);
            if (StringUtils.isNotBlank(id)) {
                String name = jsonObject.optString("name", null);
                int value = jsonObject.optInt("value", 0);
                //更新成功
                if (StringUtils.isNotBlank(name)) {
                    ParamDefinition paramDefinition = new ParamDefinition();
                    paramDefinition.setName(name);
                    paramDefinition.setValue(value);
                    paramDefinition.setId(Long.parseLong(id));
                    paramDefinition.setUpdated(new Date());

                    this.paramDefinitionManager.updateSelective(paramDefinition);
                    return responseEntity;
                }
            }
        }

        responseEntity.setCode(400);
        responseEntity.setMessage("修改失败！参数不正确！");//更新失败
        return responseEntity;
    }

    /*
    删除paramDefinition中数据
     */
    public ResponseEntity deleteParamDefinition(String id) throws CarsmartException {
        ResponseEntity responseEntity = new ResponseEntity();

        if (StringUtils.isNotBlank(id)) {//判断id是否为空
            BaseExample example = this.paramDefinitionManager.getExample();
            example.or().andPropertyEqualTo(Long.parseLong(id), "id");
            List<ParamDefinition> paramDefinitions =
                this.paramDefinitionManager.listByBaseExample(example);
            if (paramDefinitions != null && paramDefinitions.size() > 0) {
                ParamDefinition paramDefinition = paramDefinitions.get(0);
                int deviceParamId = paramDefinition.getDeviceParamId().intValue();//设备参数ID
                BaseExample example1 = this.deviceSettingManager.getExample();
                boolean tag = false;
                switch (deviceParamId) {
                    //解码类型
                    case 1:
                        example1.or().andPropertyEqualTo(Integer.parseInt(id), "decodeType");
                        if (this.deviceSettingManager.countByExample(example1) > 0) {
                            tag = true;
                        }
                        break;
                     //主机盒界面
                    case 2:
                        example1.or().andPropertyEqualTo(Integer.parseInt(id), "interfaced");
                        if (this.deviceSettingManager.countByExample(example1) > 0) {
                            tag = true;
                        }
                        break;
                     //前景和前后视角
                    case 3:
                        example1.or().andPropertyEqualTo(Integer.parseInt(id), "fbView");
                        if (this.deviceSettingManager.countByExample(example1) > 0) {
                            tag = true;
                        }
                        break;
                     //转向视角
                    case 4:
                        example1.or().andPropertyEqualTo(Integer.parseInt(id), "turnView");
                        if (this.deviceSettingManager.countByExample(example1) > 0) {
                            tag = true;
                        }
                        break;
                     //轨迹线类型
                    case 5:
                        example1.or().andPropertyEqualTo(Integer.parseInt(id), "trackType");
                        if (this.deviceSettingManager.countByExample(example1) > 0) {
                            tag = true;
                        }
                        break;
                }
                //删除失败
                if (tag) {
                    responseEntity.setCode(400);
                    responseEntity.setMessage("删除失败！请先删除相关配置！");
                    return responseEntity;
                }
            }
            this.paramDefinitionManager.deleteByPrimaryKey(Long.parseLong(id));
            return responseEntity;//删除成功
        }
        responseEntity.setCode(400);
        responseEntity.setMessage("删除失败！参数不正确！");
        return responseEntity;
    }

    /*
    根据deviceParamId获取paramDefinition列表
     */
    public JSONArray getParamDefinitionList(String paramType) throws CarsmartException {

        JSONArray list = new JSONArray();
        if (StringUtils.isNotBlank(paramType)) {

            BaseExample example = this.paramDefinitionManager.getExample();
            example.or().andPropertyEqualTo(Integer.parseInt(paramType), "deviceParamId");
            List<ParamDefinition> paramDefinitions =
                this.paramDefinitionManager.listByBaseExample(example);
            if (paramDefinitions != null && paramDefinitions.size() > 0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (ParamDefinition pd : paramDefinitions) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id", pd.getId());
                    jsonObject.put("name", pd.getName());
                    jsonObject.put("value", pd.getValue());
                    jsonObject.put("created",
                        (pd.getCreated() != null) ? sdf.format(pd.getCreated()) : "");
                    jsonObject.put("updated",
                        (pd.getUpdated() != null) ? sdf.format(pd.getUpdated()) : "");
                    list.add(jsonObject);
                }
            }
        }
        return list;
    }

    /*
    获取参数设置列表
     */
    public JSONArray getParamSettingList() throws CarsmartException {

        JSONArray list = new JSONArray();
        List<DeviceSetting> deviceSettingList = this.deviceSettingManager.list();
        if (deviceSettingList != null && deviceSettingList.size() > 0) {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (DeviceSetting ds : deviceSettingList) {
                JSONObject jsonObject = new JSONObject();

                jsonObject.put("id", ds.getId());

                //解码类型
                Integer decodeType = ds.getDecodeType();
                String[] decodeTypeStrs = queryParamDef(decodeType);
                jsonObject.put("decodeTypeId", decodeTypeStrs[0]);
                jsonObject.put("decodeTypeName", decodeTypeStrs[1]);
                jsonObject.put("decodeTypeValue", decodeTypeStrs[2]);

                //前景和前后视角
                Integer fbView = ds.getFbView();
                String[] fbVieweStrs = queryParamDef(fbView);
                jsonObject.put("fbViewId", fbVieweStrs[0]);
                jsonObject.put("fbViewName", fbVieweStrs[1]);
                jsonObject.put("fbViewValue", fbVieweStrs[2]);

                //转向视角
                Integer turnView = ds.getTurnView();
                String[] turnViewStrs = queryParamDef(turnView);
                jsonObject.put("turnViewId", turnViewStrs[0]);
                jsonObject.put("turnViewName", turnViewStrs[1]);
                jsonObject.put("turnViewValue", turnViewStrs[2]);

                //主机盒界面
                Integer interfaced = ds.getInterfaced();
                String[] interfacedStrs = queryParamDef(interfaced);
                jsonObject.put("interfacedId", interfacedStrs[0]);
                jsonObject.put("interfacedName", interfacedStrs[1]);
                jsonObject.put("interfacedValue", interfacedStrs[2]);

                //轨迹线类型
                Integer trackType = ds.getTrackType();
                String[] trackTypeStrs = queryParamDef(trackType);
                jsonObject.put("trackTypeId", trackTypeStrs[0]);
                jsonObject.put("trackTypeName", trackTypeStrs[1]);
                jsonObject.put("trackTypeValue", trackTypeStrs[2]);

                jsonObject.put("cameraCount", ds.getCameraCount());//摄像头数量
                jsonObject.put("trackCoefficient", ds.getTrackCoefficient());//轨迹系数
                jsonObject.put("wheelBase", ds.getWheelBase());//轴距
                jsonObject.put("wheelTrack", ds.getWheelTrack());//轮距
                jsonObject.put("frontWheelDist", ds.getFrontWheelDist());//前轮距车间距
                jsonObject
                    .put("screenParam", (ds.getScreenParam() != null) ? ds.getScreenParam() : "");//屏幕参数
                jsonObject
                    .put("created", (ds.getCreated() != null) ? sdf.format(ds.getCreated()) : "");//创建时间
                jsonObject
                    .put("updated", (ds.getUpdated() != null) ? sdf.format(ds.getUpdated()) : "");//更新时间

                list.add(jsonObject);
            }
        }
        return list;
    }

    /*
    根据ID查询参数定义
     */
    private String[] queryParamDef(int id) throws CarsmartException {
        BaseExample example = this.paramDefinitionManager.getExample();
        example.or().andPropertyEqualTo(id, "id");
        List<ParamDefinition> paramDefinitions =
            this.paramDefinitionManager.listByBaseExample(example);
        String name = "";//参数名称
        String value = "";//值
        String idStr = "";//ID
        if (paramDefinitions != null && paramDefinitions.size() > 0) {
            ParamDefinition paramDefinition = paramDefinitions.get(0);
            idStr = paramDefinition.getId().toString();
            name = paramDefinition.getName();
            value = paramDefinition.getValue().toString();
        }
        String[] strings = new String[3];
        strings[0] = idStr;
        strings[1] = name;
        strings[2] = value;

        return strings;
    }

    /*
    获取参数设置数据
     */
    public ResponseEntity getParamSettingsData() throws CarsmartException {

        ResponseEntity responseEntity = new ResponseEntity();
        JSONObject jsonObject = new JSONObject();

        //解码类型
        JSONArray decodeTypeArray = queryParamList(1);
        if (decodeTypeArray.size() < 1) {
            responseEntity.setCode(400);
            responseEntity.setMessage("解码类型定义为空！请先初始化数据！");
            return responseEntity;
        }
        jsonObject.put("decodeType", decodeTypeArray);

        //主机盒界面
        JSONArray interfacedArray = queryParamList(2);
        if (interfacedArray.size() < 1) {
            responseEntity.setCode(400);
            responseEntity.setMessage("主机盒界面定义为空！请先初始化数据！");
            return responseEntity;
        }
        jsonObject.put("interfaced", interfacedArray);

        //前景和前后视角
        JSONArray fbViewArray = queryParamList(3);
        if (fbViewArray.size() < 1) {
            responseEntity.setCode(400);
            responseEntity.setMessage("前景和前后视角定义为空！请先初始化数据！");
            return responseEntity;
        }
        jsonObject.put("fbView", fbViewArray);

        //转向视角
        JSONArray turnViewArray = queryParamList(4);
        if (turnViewArray.size() < 1) {
            responseEntity.setCode(400);
            responseEntity.setMessage("转向视角定义为空！请先初始化数据！");
            return responseEntity;
        }
        jsonObject.put("turnView", turnViewArray);

        //轨迹线类型
        JSONArray trackTypeArray = queryParamList(5);
        if (trackTypeArray.size() < 1) {
            responseEntity.setCode(400);
            responseEntity.setMessage("轨迹线类型定义为空！请先初始化数据！");
            return responseEntity;
        }
        jsonObject.put("trackType", trackTypeArray);

        responseEntity.setDataObject(jsonObject);

        return responseEntity;

    }

    /*
    根据deviceParamId查询参数列表
     */
    private JSONArray queryParamList(int deviceParamId) throws CarsmartException {
        JSONArray jsonArray = new JSONArray();

        BaseExample example = this.paramDefinitionManager.getExample();
        example.or().andPropertyEqualTo(deviceParamId, "deviceParamId");
        List<ParamDefinition> paramDefinitions =
            this.paramDefinitionManager.listByBaseExample(example);
        if (paramDefinitions != null && paramDefinitions.size() > 0) {
            for (ParamDefinition pd : paramDefinitions) {
                JSONObject jso = new JSONObject();
                Long id = pd.getId();
                String name = pd.getName();//名称
                Integer value = pd.getValue();//值

                jso.put("id", id);
                jso.put("value", name + "(" + value + ")");

                jsonArray.add(jso);
            }
        }
        return jsonArray;
    }

    /*
    更新参数设置
     */
    public ResponseEntity updateParamSettings(JSONObject jsonObject) throws CarsmartException {

        ResponseEntity responseEntity = new ResponseEntity();
        if (jsonObject != null && jsonObject.keySet().size() > 0) {//判断对象不为空

            String id = jsonObject.optString("id", null);
            if (StringUtils.isNotBlank(id)) {
                int decodeTypeId = jsonObject.optInt("decodeTypeId", 0);
                int interfacedId = jsonObject.optInt("interfacedId", 0);
                int fbViewId = jsonObject.optInt("fbViewId", 0);
                int turnViewId = jsonObject.optInt("turnViewId", 0);
                int trackTypeId = jsonObject.optInt("trackTypeId", 0);

                int cameraCount = jsonObject.optInt("cameraCount", 0);
                String screenParam = jsonObject.optString("screenParam", null);
                int trackCoefficient = jsonObject.optInt("trackCoefficient", 0);
                int wheelBase = jsonObject.optInt("wheelBase", 0);
                int wheelTrack = jsonObject.optInt("wheelTrack", 0);
                int frontWheelDist = jsonObject.optInt("frontWheelDist", 0);
                DeviceSetting deviceSetting = new DeviceSetting();
                deviceSetting.setId(Long.parseLong(id));

                if (decodeTypeId != 0) {
                    deviceSetting.setDecodeType(decodeTypeId);
                }
                if (interfacedId != 0) {
                    deviceSetting.setInterfaced(interfacedId);
                }
                if (fbViewId != 0) {
                    deviceSetting.setFbView(fbViewId);
                }
                if (turnViewId != 0) {
                    deviceSetting.setTurnView(turnViewId);
                }
                if (trackTypeId != 0) {
                    deviceSetting.setTrackType(trackTypeId);
                }
                if (cameraCount != 0) {
                    deviceSetting.setCameraCount(cameraCount);
                }
                if (StringUtils.isNotBlank(screenParam)) {
                    deviceSetting.setScreenParam(screenParam);
                }
                if (trackCoefficient != 0) {
                    deviceSetting.setTrackCoefficient(trackCoefficient);
                }
                if (wheelBase != 0) {
                    deviceSetting.setWheelBase(wheelBase);
                }
                if (wheelTrack != 0) {
                    deviceSetting.setWheelTrack(wheelTrack);
                }
                if (frontWheelDist != 0) {
                    deviceSetting.setFrontWheelDist(frontWheelDist);
                }
                deviceSetting.setUpdated(new Date());

                //更新成功
                this.deviceSettingManager.updateSelective(deviceSetting);
                return responseEntity;
            }
        }

        responseEntity.setCode(400);
        responseEntity.setMessage("修改失败！参数不正确！");//更新失败
        return responseEntity;
    }

    /*
    新增参数设置
     */
    public ResponseEntity addParamSettings(JSONObject jsonObject) throws CarsmartException {

        ResponseEntity responseEntity = new ResponseEntity();
        if (jsonObject != null && jsonObject.keySet().size() > 0) {

            int decodeTypeId = jsonObject.optInt("decodeTypeId", 0);
            int interfacedId = jsonObject.optInt("interfacedId", 0);
            int fbViewId = jsonObject.optInt("fbViewId", 0);
            int turnViewId = jsonObject.optInt("turnViewId", 0);
            int trackTypeId = jsonObject.optInt("trackTypeId", 0);

            int cameraCount = jsonObject.optInt("cameraCount", 0);
            String screenParam = jsonObject.optString("screenParam", null);
            int trackCoefficient = jsonObject.optInt("trackCoefficient", 0);
            int wheelBase = jsonObject.optInt("wheelBase", 0);
            int wheelTrack = jsonObject.optInt("wheelTrack", 0);
            int frontWheelDist = jsonObject.optInt("frontWheelDist", 0);
            DeviceSetting deviceSetting = new DeviceSetting();

            if (decodeTypeId != 0) {
                deviceSetting.setDecodeType(decodeTypeId);
            }
            if (interfacedId != 0) {
                deviceSetting.setInterfaced(interfacedId);
            }
            if (fbViewId != 0) {
                deviceSetting.setFbView(fbViewId);
            }
            if (turnViewId != 0) {
                deviceSetting.setTurnView(turnViewId);
            }
            if (trackTypeId != 0) {
                deviceSetting.setTrackType(trackTypeId);
            }
            if (cameraCount != 0) {
                deviceSetting.setCameraCount(cameraCount);
            }
            if (StringUtils.isNotBlank(screenParam)) {
                deviceSetting.setScreenParam(screenParam);
            }
            if (trackCoefficient != 0) {
                deviceSetting.setTrackCoefficient(trackCoefficient);
            }
            if (wheelBase != 0) {
                deviceSetting.setWheelBase(wheelBase);
            }
            if (wheelTrack != 0) {
                deviceSetting.setWheelTrack(wheelTrack);
            }
            if (frontWheelDist != 0) {
                deviceSetting.setFrontWheelDist(frontWheelDist);
            }
            deviceSetting.setCreated(new Date());
            deviceSetting.setUpdated(new Date());

            //新增成功
            this.deviceSettingManager.insert(deviceSetting);
            return responseEntity;
        }

        //新增失败
        responseEntity.setCode(400);
        responseEntity.setMessage("修改失败！参数不正确！");
        return responseEntity;
    }

    /*
    根据ID删除参数设置
     */
    public ResponseEntity deleteParamSettings(String id) throws CarsmartException {

        ResponseEntity responseEntity = new ResponseEntity();
        if (StringUtils.isNotBlank(id)) {

            //删除成功
            this.deviceSettingManager.deleteByPrimaryKey(Long.parseLong(id));
            return responseEntity;
        }

        //删除失败
        responseEntity.setCode(400);
        responseEntity.setMessage("删除失败！参数不正确！");
        return responseEntity;

    }
}
